package com.tianji.learning.task;

import com.tianji.common.utils.CollUtils;
import com.tianji.learning.constants.RedisConstants;
import com.tianji.learning.domain.po.PointsBoard;
import com.tianji.learning.domain.po.PointsBoardSeason;
import com.tianji.learning.service.IPointsBoardSeasonService;
import com.tianji.learning.service.IPointsBoardService;
import com.tianji.learning.utils.TableInfoContext;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.tianji.learning.constants.LearningConstants.POINTS_BOARD_TABLE_PREFIX;

@Component
@RequiredArgsConstructor
public class PointsBoardPersistentHandler {

    private final IPointsBoardService pointsBoardService;
    private final IPointsBoardSeasonService pointsBoardSeasonService;
    private final StringRedisTemplate redisTemplate;
    /**
     * 创建上赛季（上个月） 榜单表
     */
//    @Scheduled(cron = "0 0 3 1 * ?") // 每月1号凌晨3点执行
    @XxlJob("createTableJob")
    public void createPointsBoardTableOfLastSeason(){
        // 1. 获取上个月当前时间点
        LocalDate time = LocalDate.now().minusMonths(1);
        // 2. 查询赛季表获得赛季id
        PointsBoardSeason one = pointsBoardSeasonService.lambdaQuery()
                .le(PointsBoardSeason::getBeginTime, time)
                .ge(PointsBoardSeason::getEndTime, time)
                .one();
        if (one == null){
            return;
        }
        // 3. 创建上赛季榜单表
        pointsBoardService.createPointsBoardLatestTable(one.getId());
    }

    // 持久化上赛季（上个月的）排行榜数据 到db中
    @XxlJob("savePointsBoard2DB") // 任务 名字要和xxljob控制台  任务的jobhandler值保持一致
    public void savePointsBoard2DB(){
        // 1. 获取上个月 当前时间点
        LocalDate time = LocalDate.now().minusMonths(1);
        // 2. 查询赛季表points_board_season 获取上赛季信息
        PointsBoardSeason one = pointsBoardSeasonService.lambdaQuery()
                .le(PointsBoardSeason::getBeginTime, time)
                .ge(PointsBoardSeason::getEndTime, time)
                .one();
        if (one == null){
            return;
        }
        // 3. 计算动态表名  并存入 threadlocal
        String tableName = POINTS_BOARD_TABLE_PREFIX + one.getId();
        TableInfoContext.setInfo(tableName);
        // 4. 分页获取redis上赛季积分排行榜数据
        String format = time.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String key = RedisConstants.POINTS_BOARD_KEY_PREFIX + format;
        int shardIndex = XxlJobHelper.getShardIndex(); // 当前分片索引
        int shardTotal = XxlJobHelper.getShardTotal();  // 分页总数
        int pageNo = shardIndex + 1; // 页码
        int pageSize = 1000;
        while (true){
            List<PointsBoard> pointsBoardList = pointsBoardService.queryCurrentBoard(key, pageNo, pageSize);
            if (CollUtils.isEmpty(pointsBoardList)){
                break;
            }
            pageNo+=shardTotal;
            // 5. 持久化到db相应的赛季中
            for (PointsBoard board : pointsBoardList) {
                board.setId(board.getRank().longValue());
                board.setRank(null);
            }
            pointsBoardService.saveBatch(pointsBoardList);
        }
        // 6. 清空threadlocal中数据
        TableInfoContext.remove();
    }

    @XxlJob("clearPointsBoardFromRedis")
    public void clearPointsBoardFromRedis(){
        // 获取上月时间
        LocalDate time = LocalDate.now().minusMonths(1);
        // 计算key
        String format = time.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String key = RedisConstants.POINTS_BOARD_KEY_PREFIX + format;
        // 删除
        redisTemplate.unlink(key);
    }

}
